﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.AdvTree;
using System.Data.Linq;
using System.Collections;
using System.Linq;
using Cashier;
using NomClasses;

namespace NomCafe
{
    public partial class Main_Cashier : DevComponents.DotNetBar.Office2007Form
    {
        public static Node selectNode;
        bool isSelectTableNode = false;
        public static nom_table currenTable;
        
        public Main_Cashier()
        {
            InitializeComponent();
        }

        private void Main_Cashier_Load(object sender, EventArgs e)
        {
            panelEx1.Text = String.Format(languageCashier.WORDSHIFT, Lib_Cashier.fullname);
            Load_InformationTable();            
        }

        private void Load_InformationTable()
        {
            // Định nghĩa group node style
            ElementStyle groupStyle = new ElementStyle();

            //Định nghĩa sub-item style
            ElementStyle subItemStyle = new ElementStyle();
            subItemStyle.TextColor = Color.Gray;
            subItemStyle.Name = "subitemstyle";

            // Thiết lập group style
            groupStyle = new ElementStyle();
            groupStyle.TextColor = Color.SlateGray;
            groupStyle.Font = new Font(advTreeTableCoffee.Font.FontFamily, 9f, FontStyle.Bold);
            groupStyle.Name = "groupstyle";
            advTreeTableCoffee.Styles.Add(groupStyle);

            // Style for contact name
            subItemStyle = new ElementStyle();
            subItemStyle.TextColor = Color.SlateGray;
            subItemStyle.Name = "subitemstyle";
            advTreeTableCoffee.Styles.Add(subItemStyle);

            // Style for phone cell
            subItemStyle = new ElementStyle();
            subItemStyle.TextColor = Color.Maroon;
            subItemStyle.Font = new Font(advTreeTableCoffee.Font.FontFamily, 10f, FontStyle.Bold);
            subItemStyle.TextAlignment = eStyleTextAlignment.Center;
            subItemStyle.Name = "subitemphone";
            advTreeTableCoffee.Styles.Add(subItemStyle);
            #region List customer
            ArrayList customers = new ArrayList();
            NomClasses.NomDataContext nc = new NomClasses.NomDataContext();
            System.Data.Linq.Table<NomClasses.nom_area> areas = nc.nom_areas;
            foreach (NomClasses.nom_area arr in areas)
            {
                foreach (NomClasses.nom_table tb in arr.nom_tables)
                {
                    customers.Add(new Customer("", "", arr.name, tb.code));
                }
            }
            #endregion
            advTreeTableCoffee.GroupingMembers = "Country";
            advTreeTableCoffee.DisplayMembers = "Contact,Phone";
            advTreeTableCoffee.GroupNodeCreated += new DevComponents.DotNetBar.Controls.DataNodeEventHandler(AdvTreeTableCoffeeGroupNodeCreated);
            advTreeTableCoffee.DataNodeCreated += new DevComponents.DotNetBar.Controls.DataNodeEventHandler(AdvTreeTableCoffeeDataNodeCreated);
            advTreeTableCoffee.TileSize = new Size(64, 50);
            advTreeTableCoffee.DataSource = customers;

        }

        // Tạo bàn 
        void AdvTreeTableCoffeeDataNodeCreated(object sender, DevComponents.DotNetBar.Controls.DataNodeEventArgs e)
        {
            e.Node.ImageIndex = 0;
            e.Node.ImageAlignment = eCellPartAlignment.CenterBottom;
            e.Node.Cells[1].StyleNormal = advTreeTableCoffee.Styles["subitemstyle"];
            e.Node.Cells[1].StyleNormal = advTreeTableCoffee.Styles["subitemphone"];
        }
        // Tạo khu vực
        void AdvTreeTableCoffeeGroupNodeCreated(object sender, DevComponents.DotNetBar.Controls.DataNodeEventArgs e)
        {
            e.Node.Style = advTreeTableCoffee.Styles["groupstyle"];
        }

        #region Customer Class
        internal class Customer
        {
            /// <summary>
            /// Initializes a new instance of the Customer class.
            /// </summary>
            /// <param name="company"></param>
            /// <param name="contact"></param>
            /// <param name="country"></param>
            /// <param name="phone"></param>
            public Customer(string company, string contact, string country, string phone)
            {
                Company = company;
                Contact = contact;
                Country = country;
                Phone = phone;
            }
            private string _Company;
            public string Company
            {
                get { return _Company; }
                set
                {
                    _Company = value;
                }
            }
            private string _Contact;
            public string Contact
            {
                get { return _Contact; }
                set
                {
                    _Contact = value;
                }
            }
            private string _Country;
            public string Country
            {
                get { return _Country; }
                set
                {
                    _Country = value;
                }
            }
            private string _Phone;
            public string Phone
            {
                get { return _Phone; }
                set
                {
                    _Phone = value;
                }
            }
        }
        #endregion

        private void btnExit_Click(object sender, EventArgs e)
        {
            bool isTable = false;
            
            for (int i = 0; i < advTreeTableCoffee.Nodes.Count; i++)
            {
                int j = 0;
                while(j != advTreeTableCoffee.Nodes[i].Nodes.Count)
                {                    
                    if (advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex == 2 || advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex == 3)
                        isTable = true;
                    j++;
                }                
            }
            if (isTable == true)
            {
                MessageBox.Show(languageCashier.EXIT_ERROR);
            }
            else
            {
                Application.Exit();
            }
        }

        private void advTreeTableCoffee_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            // Lấy node đang chọn để xử lý nút chọn bàn trên form Main_Cashier
            selectNode = e.Node;
            // Lấy node đang chọn truyền vào class Lib_Cashier để xử lý thông tin cho các form khác
            Lib_Cashier.currentNodeName = e.Node.Cells[1].Text.ToString();
            Lib_Cashier.currentRootName = e.Node.Parent.Text.ToString();

            NomDataContext nc = new NomDataContext();
            // Lấy table_id của bàn đang chọn
            nom_table table = nc.nom_tables.Single(t => t.code == Lib_Cashier.currentNodeName &&
                                                        t.nom_area.name == Lib_Cashier.currentRootName);
            currenTable = table;
            // Xử lý thay đổi nút chọn bàn khi chọn node trên form Main_Cashier
            if (e.Node.ImageIndex == 1)
            {
                listViewInformationTable.Items.Clear();
                isSelectTableNode = false;
                btnSelectTable.Enabled = true;
                ribbonBar8.Text = languageCashier.SELECT_TABLE;
                btnManagerItem.Enabled = false;                
                btnChangeTable.Enabled = false;
                btnGroupTable.Enabled = false;
                btnPayTable.Enabled = false;                
            }
            else
            {
                listViewInformationTable.Items.Clear();
                isSelectTableNode = true;
                ribbonBar8.Text = languageCashier.UNSELECT_TABLE;
                btnManagerItem.Enabled = true;
                getItemsTable();
            }
        }

        private void btnSelectTable_Click(object sender, EventArgs e)
        {
            // Nếu bàn đã chọn thì chạy else , chưa chọn thì chạy if :
            if (isSelectTableNode)
            {
                setUnselectTable();
                // Hủy bill của bàn khi bỏ chọn bàn
                NomDataContext nc = new NomDataContext();
                var deleteTableBill = from tableBill in nc.nom_bills
                                      where tableBill.table_id == currenTable.id && tableBill.time_end == null
                                      select tableBill;
                nc.nom_bills.DeleteAllOnSubmit(deleteTableBill);
                nc.SubmitChanges();
                isSelectTableNode = false;
            }
            else
            {
                setSelectTable();
                createBill();
                isSelectTableNode = true;
            }            
        }

        private void advTreeTableCoffee_NodeMouseMove(object sender, TreeNodeMouseEventArgs e)
        {
            if (e.Node.Style != advTreeTableCoffee.Styles["groupstyle"] && (e.Node.ImageIndex != 2) && (e.Node.ImageIndex != 3))
            {
                e.Node.ImageIndex = 1;
            }
        }

        private void advTreeTableCoffee_NodeMouseLeave(object sender, TreeNodeMouseEventArgs e)
        {
            if ((e.Node.Style != advTreeTableCoffee.Styles["groupstyle"]) && (e.Node.ImageIndex != 2) && (e.Node.ImageIndex != 3))
            {
                e.Node.ImageIndex = 0;
            }
        }

        private void advTreeTableCoffee_NodeDoubleClick(object sender, TreeNodeMouseEventArgs e)
        {
            if (e.Node.ImageIndex == 1)
            {
                createBill();
            }
            setSelectTable();            
        }

        private void btnManagerItem_Click(object sender, EventArgs e)
        {
            frmAddItem addItem = new frmAddItem();
            addItem.ShowDialog(this);
        }

        private void btnChangeTable_Click(object sender, EventArgs e)
        {
            // Lấy danh sách các bàn đã có người ngồi
            Lib_Cashier.listSelectTable = "";
            int i = 0;
            int parentNode = advTreeTableCoffee.Nodes.Count;
            while (i != parentNode)
            {
                for (int j = 0; j < advTreeTableCoffee.Nodes[i].Nodes.Count; j++)
                {
                    if (advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex == 2)
                    {
                        Lib_Cashier.listSelectTable = Lib_Cashier.listSelectTable + advTreeTableCoffee.Nodes[i].Text + "," + advTreeTableCoffee.Nodes[i].Nodes[j].Cells[1].Text + ";";
                    }
                }
                i++;
            }
            // Hiển thị form changeTable
            frmChangeTable changeTable = new frmChangeTable(this);
            changeTable.ShowDialog();            
        }

        // Lấy dữ liệu món trên bàn đã có khách 
        public void getItemsTable()
        {
            listViewInformationTable.Items.Clear();
            NomDataContext nc = new NomDataContext();
            nom_bill bill_data = nc.nom_bills.Single(bill => bill.table_id == currenTable.id && bill.time_end == null);
            
            var bill_detail = from bill_de in nc.nom_bill_details
                              where bill_de.bill_id == bill_data.id
                              select bill_de;
            
            decimal tongtien = 0;
            if (bill_detail.Count() != 0)
            {                
                foreach (var itemOnBill in bill_detail)
                {
                    tongtien = itemOnBill.cash + tongtien;
                    string[] row = {itemOnBill.quantity.ToString(), // số lượng                                                                                                                  
                            String.Format("{0:0,0}",itemOnBill.cash)};// thành tiền
                    listViewInformationTable.Items.Add(itemOnBill.nom_item.name).SubItems.AddRange(row);
                }
                string[] endRow = { "", String.Format("{0:0,0}", tongtien) };
                listViewInformationTable.Items.Add(languageCashier.TOTAL).SubItems.AddRange(endRow);
                btnChangeTable.Enabled = true;
                btnGroupTable.Enabled = true;
                btnPayTable.Enabled = true;
                btnSelectTable.Enabled = false;
            }
            else
            {
                btnChangeTable.Enabled = false;
                btnGroupTable.Enabled = false;
                btnPayTable.Enabled = false;
                btnSelectTable.Enabled = true;
            }
        }

        // Tạo mới nom_bill khi chọn bàn
        private void createBill()
        {            
            NomDataContext nc = new NomDataContext();            
            nom_bill billData = new nom_bill();
            billData.cashier = 1;
            //billData.waiter_id = 1;            
            billData.table_id = currenTable.id;
            billData.time_start = DateTime.Now;
            billData.time_end = null;

            nc.nom_bills.InsertOnSubmit(billData);
            nc.SubmitChanges();
        }

        // Chuyển dữ liệu qua bàn đã chọn ở frmChangeTable
        public void ChangeTable()
        {
            string [] table = Lib_Cashier.nodeNameChangeTable.Split(',');
            int i = 0;
            int areaNode = this.advTreeTableCoffee.Nodes.Count;
            while (i != areaNode)
            {
                if (advTreeTableCoffee.Nodes[i].Text == table[0])
                {
                    for (int j = 0; j < advTreeTableCoffee.Nodes[i].Nodes.Count; j++)
                    {
                        if (advTreeTableCoffee.Nodes[i].Nodes[j].Cells[1].Text == table[1])
                        {
                            advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex = 2;
                            NomDataContext nc = new NomDataContext();
                            nom_table tableChange = nc.nom_tables.Single(t => t.code == table[1] && t.nom_area.name == table[0]);
                            nom_bill billChange = nc.nom_bills.Single(b => b.table_id == currenTable.id && b.time_end == null);
                            billChange.table_id = tableChange.id;

                            var billDetail = from bDetail in nc.nom_bill_details
                                             where bDetail.bill_id == billChange.id
                                             select bDetail;
                            foreach(var detail in billDetail)
                            {
                                detail.group_table = billChange.nom_table.code;
                            }                           

                            nc.SubmitChanges();
                            ChangeTableSelectedToNull();
                            break;
                        }
                    }
                    break;
                }
                i++;
            }
        }

        // Chuyển bàn đã chọn ở form Main_Cashier thành bàn trống
        private void ChangeTableSelectedToNull()
        {
            setUnselectTable();            
        }

        private void btnGroupTable_Click(object sender, EventArgs e)
        {
            // Lấy danh sách các bàn đã có người ngồi
            Lib_Cashier.listSelectTable = "";
            int i = 0;
            int parentNode = advTreeTableCoffee.Nodes.Count;
            while (i != parentNode)
            {
                for (int j = 0; j < advTreeTableCoffee.Nodes[i].Nodes.Count; j++)
                {
                    if (advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex == 2)
                    {
                        Lib_Cashier.listSelectTable =   Lib_Cashier.listSelectTable + advTreeTableCoffee.Nodes[i].Text + "," +
                                                        advTreeTableCoffee.Nodes[i].Nodes[j].Cells[1].Text + ";";
                    }
                }
                i++;
            }
            frmGroupTable groupTable = new frmGroupTable(this);
            groupTable.ShowDialog();
        }

        // Chuyển dữ liệu các bàn chọn ghép ở frmGroupTable vào bàn gốc
        public void GroupTable()
        {
            int i = 0;
            int areaNode = this.advTreeTableCoffee.Nodes.Count;
            while (i != areaNode)
            {
                if (advTreeTableCoffee.Nodes[i].Text == Lib_Cashier.currentRootName)
                {
                    for (int j = 0; j < advTreeTableCoffee.Nodes[i].Nodes.Count; j++)
                    {
                        if (advTreeTableCoffee.Nodes[i].Nodes[j].Cells[1].Text == Lib_Cashier.currentNodeName)
                        {
                            // Lấy bill id của bàn gốc
                            advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex = 3;
                            NomDataContext nc = new NomDataContext();
                            nom_bill currenTableBill = nc.nom_bills.Single(b => b.table_id == currenTable.id && b.time_end == null);
                            GroupTableSelectedToNull(currenTableBill);
                            break;
                        }
                    }
                    break;
                }
                i++;
            }
        }

        // Chuyển các bàn chọn ghép thành bàn trống
        private void GroupTableSelectedToNull(nom_bill billCurrenTable)
        {
            int i = 0;
            int parentNode = this.advTreeTableCoffee.Nodes.Count;
            string[] selectTable = Lib_Cashier.nodeNameChangeTable.Split(';');
            foreach (string tables in selectTable)
            {
                string[] table = tables.Split(',');
                while (i != parentNode)
                {
                    if (advTreeTableCoffee.Nodes[i].Text == table[0])
                    {
                        for (int j = 0; j < advTreeTableCoffee.Nodes[i].Nodes.Count; j++)
                        {
                            if (advTreeTableCoffee.Nodes[i].Nodes[j].Cells[1].Text == table[1])
                            {
                                // Chuyển dữ liệu của bàn được chọn vào bàn gốc
                                advTreeTableCoffee.Nodes[i].Nodes[j].ImageIndex = 0;
                                NomDataContext nc = new NomDataContext();
                                nom_table tableGroup = nc.nom_tables.Single(t => t.code == table[1] && t.nom_area.name == table[0]);
                                nom_bill billGroup = nc.nom_bills.Single(b => b.table_id == tableGroup.id && b.time_end == null);                                
                                billGroup.time_end = DateTime.Now;
                                var billDetailGroup = from billDetail in nc.nom_bill_details
                                                      where billDetail.bill_id == billGroup.id
                                                      select billDetail;
                                foreach (var bill in billDetailGroup)
                                {
                                    bill.bill_id = billCurrenTable.id;
                                    bill.group_table = tableGroup.code;
                                }
                                nc.SubmitChanges();
                                getItemsTable();
                                break;
                            }
                        }
                        break;
                    }
                    i++;
                }
            }            
        }

        private void btnPayTable_Click(object sender, EventArgs e)
        {
            frmPayTable payTable = new frmPayTable(this);
            payTable.ShowDialog();
        }

        private void setSelectTable()
        {
            selectNode.ImageIndex = 2;
            ribbonBar8.Text = languageCashier.UNSELECT_TABLE;
            btnManagerItem.Enabled = true;
        }

        public void setUnselectTable()
        {
            selectNode.ImageIndex = 1;
            ribbonBar8.Text = languageCashier.SELECT_TABLE;
            btnSelectTable.Enabled = true;
            btnManagerItem.Enabled = false;
            btnChangeTable.Enabled = false;
            btnGroupTable.Enabled = false;
            btnPayTable.Enabled = false;
            listViewInformationTable.Items.Clear();
        }

        private void btnInformation_Click(object sender, EventArgs e)
        {
            frmChangePassword change = new frmChangePassword();
            change.ShowDialog();
        }
        
    }
}
